package com.example.hjt_java_web_homework3.filter;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author Li Chun Hei
 * @date 31/10/2025
 * @description
 */
@WebFilter("/api/*")
public class AuthenticationFilter implements Filter {
    private static final Logger logger = LogManager.getLogger(AuthenticationFilter.class);

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession(false);

        String path = httpRequest.getRequestURI();

        // 允许登录和公开接口通过
        if (path.endsWith("/api/auth/login") || path.contains("/public")) {
            chain.doFilter(request, response);
            return;
        }

        // 检查用户是否已登录
        if (session == null || session.getAttribute("user") == null) {
            logger.warn("Unauthorized access attempt to: {}", path);
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpResponse.getWriter().write("{\"success\":false,\"message\":\"Unauthorized\"}");
            return;
        }

        logger.debug("User authorized for: {}", path);
        chain.doFilter(request, response);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("AuthenticationFilter initialized");
    }

    @Override
    public void destroy() {
        logger.info("AuthenticationFilter destroyed");
    }}
